package com.example.test.dialog

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView

class AlertDialog  constructor(context: Context, themeResId: Int): Dialog(context,themeResId), DialogInterface {

    private var title: TextView ?= null
    private var msg: TextView ?= null
    private var positiveBtn: Button ?= null
    private var negativeBtn: Button ?= null
    private var neutralBtn: Button  ?= null
    private var mNegativeButtonListener: OnClickListener ?= null
    private var mPositiveButtonListener: OnClickListener ?= null
    private var mNeutralButtonListener: OnClickListener ?= null
    private var mTitle: String ?= null
    private var message: String ?= null

    private val animationTime = 1 * 300
    private var mDuration = animationTime.toLong()
    private var isNotCancelable: Boolean = false
    private var dialogLl: LinearLayout ?= null
    private var mRelativeLayout: RelativeLayout ?= null
    private var loadingRl: RelativeLayout ?= null
    private var loadingText: TextView ?= null
    private var isTouch: Boolean = true
    private var isOpen :Boolean = false

    companion object {
        fun getInstance(context: Context,themeResId: Int) : AlertDialog {
            val instance: AlertDialog by lazy { AlertDialog(context, themeResId) }
            return instance
        }
    }

    init {
        initView(context)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val params = window.attributes
        params.height = ViewGroup.LayoutParams.MATCH_PARENT
        params.width = ViewGroup.LayoutParams.MATCH_PARENT
        window.attributes = params as android.view.WindowManager.LayoutParams
    }

    private fun initView(context: Context?){
        val rootView = LayoutInflater.from(context).inflate(R.layout.dialog, null)
        mRelativeLayout = rootView.findViewById<View>(R.id.dialog_main) as RelativeLayout
        title = rootView.findViewById<View>(R.id.dialog_title)as TextView
        msg = rootView.findViewById<View>(R.id.dialog_msg)as TextView
        positiveBtn = rootView.findViewById<View>(R.id.positive_btn)as Button
        negativeBtn = rootView.findViewById<View>(R.id.negative_btn)as Button
        neutralBtn = rootView.findViewById<View>(R.id.neutral_btn)as Button
        dialogLl = rootView.findViewById<View>(R.id.dialog_ll) as LinearLayout
        loadingRl = rootView.findViewById<View>(R.id.loading_rl) as RelativeLayout
        loadingText = rootView.findViewById<View>(R.id.loading_text) as TextView
        this.setContentView(rootView)

        if (isEmpty(mTitle)) {
            title!!.visibility = View.GONE
        }else{
            title!!.text = mTitle
        }
        msg!!.text = message
        this.setOnShowListener {
            entryAnim(mRelativeLayout)
        }
        mRelativeLayout!!.setOnClickListener({
            if (isNotCancelable){
                dismiss()
            }
        })
    }

    fun loadDialog(isLoading: Boolean): AlertDialog {
        if(isLoading){
            dialogLl!!.visibility = View.GONE
            loadingRl!!.visibility = View.VISIBLE
        }else{
            loadingRl!!.visibility = View.GONE
            dialogLl!!.visibility = View.VISIBLE
        }
        return this
    }

    fun isCancelableOnTouchOutside(cancelable: Boolean): AlertDialog {
        this.setCanceledOnTouchOutside(cancelable)
        return this
    }

    //设置该对话框是否是可撤销的
    fun isCancelable(isCancelable: Boolean): AlertDialog {
        this.isNotCancelable = isCancelable
        this.setCancelable(isCancelable)
        return this
    }

    fun setTitleColor(colorString: String): AlertDialog {
        msg!!.setTextColor(Color.parseColor(colorString))
        return this
    }

    fun setTitle(string: String): AlertDialog {
        title!!.text = string
        return this
    }

    fun setLoadingText(text: CharSequence?): AlertDialog {
        loadingText!!.text = text
        return this
    }

    fun setMessage(text: CharSequence?): AlertDialog {
        msg!!.text = text
        return this
    }

    fun setTitleColor(color: Int): AlertDialog {
        msg!!.setTextColor(color)
        return this
    }

    fun setTitleSize(size: Int): AlertDialog {
        msg!!.textSize = size.toFloat()
        return this
    }

    fun setMsgColor(colorString: String): AlertDialog {
        msg!!.setTextColor(Color.parseColor(colorString))
        return this
    }

    fun setMsgColor(color: Int): AlertDialog {
        msg!!.setTextColor(color)
        return this
    }

    fun setMsgSize(size: Int): AlertDialog {
        msg!!.textSize = size.toFloat()
        return this
    }

    //是否打开动画
    fun isOpen(isOpen :Boolean): AlertDialog {
        this.isOpen = isOpen
        return this
    }

    fun setDuration(duration: Long) : AlertDialog {
        this.mDuration = duration
        return this
    }

    fun isEmpty(msg: CharSequence?): Boolean {
        return !TextUtils.isEmpty(msg)
    }

    interface OnClickListener {
        fun onClick(dialog: AlertDialog?, which: Int)
    }

    fun setPositiveButton(text: CharSequence?, listener: OnClickListener): AlertDialog {
        positiveBtn!!.visibility = View.VISIBLE
        positiveBtn!!.text = text
        this.mPositiveButtonListener = listener
        positiveBtn!!.setOnClickListener {
            if(isTouch) {
                mPositiveButtonListener!!.onClick(this, 1)
                isTouch = false
            }
        }
        return this
    }

    fun setNegativeButton(text: CharSequence?, listener: OnClickListener): AlertDialog {
        negativeBtn!!.visibility = View.VISIBLE
        negativeBtn!!.text = text
        mNegativeButtonListener = listener
        negativeBtn!!.setOnClickListener {
            if(isTouch) {
                mNegativeButtonListener!!.onClick(this, 2)
                isTouch=false
            }
        }
        return this
    }


    fun setNeutralButton(text: CharSequence?, listener: OnClickListener): AlertDialog {
        neutralBtn!!.visibility = View.VISIBLE
        neutralBtn!!.text = text
        mNeutralButtonListener = listener
        neutralBtn!!.setOnClickListener {
            if(isTouch){
                mNeutralButtonListener!!.onClick(this,3)
                isTouch = false
            }
        }
        return this
    }

    override fun onBackPressed() {
        super.onBackPressed()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            exitAnim(mRelativeLayout)
        } else {
            super.onBackPressed()
        }
    }

    override fun dismiss() {
        if (isOpen){
            if (mRelativeLayout != null) {
                exitAnim(mRelativeLayout)
            }
        }else{
            super.dismiss()
        }
        isTouch = true
    }


   private var isAnimation: Boolean = false

    fun entryAnim(view: View?) {
        if (isAnimation) {
            return
        }
        val animatorSet = AnimatorSet()
        if (mDuration != mDuration) {
            animatorSet.duration = Math.abs(mDuration)
        }
        animatorSet.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationStart(animation: Animator) {
                super.onAnimationStart(animation)
                isAnimation = true
            }

            override fun onAnimationEnd(animation: Animator) {
                super.onAnimationEnd(animation)
                //防止动画在返回键时重复执行
                isAnimation = false
            }
        })
        //属性动画集合，Y轴向上移动460f，alpha透明度
        animatorSet.playTogether(
                ObjectAnimator.ofFloat(view, "TranslationY",460f, 0f).setDuration(mDuration),
                ObjectAnimator.ofFloat(view, "Alpha", 0f, 1f).setDuration(mDuration * 3 / 2)
        )
        animatorSet.start()
    }

    fun exitAnim(view: View?){
        if (isAnimation) {
            return
        }
        val animatorSet = AnimatorSet()
        animatorSet.playTogether(
                ObjectAnimator.ofFloat(view, "TranslationY", 0f, 460f).setDuration(mDuration),
                ObjectAnimator.ofFloat(view, "Alpha", 1f, 0f).setDuration(mDuration / 2 * 3)
        )
        animatorSet.addListener(object :AnimatorListenerAdapter(){

            override fun onAnimationStart(animation: Animator?) {
                super.onAnimationStart(animation)
                isAnimation = true
            }

            override fun onAnimationEnd(animation: Animator?) {
                super.onAnimationEnd(animation)
                isAnimation = false
                if (mRelativeLayout!= null) {
                    mRelativeLayout!!.post({ super@AlertDialog.dismiss() })
                }
            }

            override fun onAnimationRepeat(animation: Animator?) {
                super.onAnimationRepeat(animation)
            }
        })
        animatorSet.start()
    }
}